import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/habit.dart';
import '../services/habit_provider.dart';
import '../utils/app_theme.dart';

class TemplatesScreen extends StatelessWidget {
  const TemplatesScreen({super.key});
  
  // Predefined template habits
  final List<Map<String, dynamic>> _templates = const [
    {
      'name': '晨间冥想',
      'description': '培养专注力，减轻压力，提高注意力',
      'icon': 'meditation',
      'color': 0xFF9C27B0,
      'frequency': '每天',
      'amount': '10分钟',
    },
    {
      'name': '阅读',
      'description': '扩展知识面，提高创造力和语言能力',
      'icon': 'book',
      'color': 0xFF2196F3,
      'frequency': '每天',
      'amount': '30分钟',
    },
    {
      'name': '喝水',
      'description': '保持身体水分，提高新陈代谢，增强免疫力',
      'icon': 'water',
      'color': 0xFF00BCD4,
      'frequency': '每天',
      'amount': '8杯水',
    },
    {
      'name': '运动',
      'description': '增强体质，改善心情，预防疾病',
      'icon': 'exercise',
      'color': 0xFFFF9800,
      'frequency': '每天',
      'amount': '30分钟',
    },
    {
      'name': '写日记',
      'description': '整理思绪，记录生活，培养表达能力',
      'icon': 'notes',
      'color': 0xFF4CAF50,
      'frequency': '每天',
      'amount': '晚上',
    },
    {
      'name': '睡前阅读',
      'description': '改善睡眠质量，放松身心',
      'icon': 'book',
      'color': 0xFF3F51B5,
      'frequency': '每天',
      'amount': '20分钟',
    },
    {
      'name': '学习新技能',
      'description': '保持大脑活力，不断进步',
      'icon': 'study',
      'color': 0xFFE91E63,
      'frequency': '每周',
      'amount': '2小时',
    },
    {
      'name': '早起',
      'description': '充分利用早晨时间，保持良好的生活节奏',
      'icon': 'sleep',
      'color': 0xFFFF5722,
      'frequency': '每天',
      'amount': '6:30前起床',
    },
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('习惯模板'),
      ),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          // Templates description
          Container(
            padding: const EdgeInsets.all(16),
            decoration: AppTheme.cardDecoration,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '习惯建议',
                  style: AppTheme.subheadingStyle,
                ),
                const SizedBox(height: 8),
                const Text(
                  '以下是一些常见的有益习惯，选择适合你的添加到个人习惯中',
                  style: AppTheme.bodyStyle,
                ),
                const SizedBox(height: 16),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Icon(Icons.info_outline, color: AppTheme.accentColor),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        '添加适合自己的习惯更容易坚持，建议每次只添加1-2个新习惯',
                        style: TextStyle(
                          color: AppTheme.textSecondaryColor,
                          fontSize: 14,
                          fontStyle: FontStyle.italic,
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          const SizedBox(height: 20),
          
          // Templates grid
          GridView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              childAspectRatio: 0.8,
              crossAxisSpacing: 12,
              mainAxisSpacing: 12,
            ),
            itemCount: _templates.length,
            itemBuilder: (context, index) {
              final template = _templates[index];
              return _buildTemplateCard(context, template);
            },
          ),
        ],
      ),
    );
  }
  
  Widget _buildTemplateCard(BuildContext context, Map<String, dynamic> template) {
    IconData iconData;
    
    // Convert string icon name to IconData
    switch (template['icon']) {
      case 'water':
        iconData = Icons.water_drop;
        break;
      case 'exercise':
        iconData = Icons.fitness_center;
        break;
      case 'book':
        iconData = Icons.book;
        break;
      case 'meditation':
        iconData = Icons.self_improvement;
        break;
      case 'notes':
        iconData = Icons.note;
        break;
      case 'sleep':
        iconData = Icons.nightlight;
        break;
      case 'study':
        iconData = Icons.school;
        break;
      default:
        iconData = Icons.list;
    }
    
    return Container(
      decoration: AppTheme.cardDecoration,
      child: InkWell(
        onTap: () => _showAddTemplateDialog(context, template),
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Color(template['color']).withOpacity(0.1),
                  shape: BoxShape.circle,
                ),
                child: Icon(
                  iconData,
                  color: Color(template['color']),
                  size: 32,
                ),
              ),
              const SizedBox(height: 12),
              Text(
                template['name'],
                style: AppTheme.subheadingStyle.copyWith(fontSize: 16),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 4),
              Text(
                '${template['frequency']} · ${template['amount']}',
                style: AppTheme.smallTextStyle,
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 12),
              Text(
                template['description'],
                style: const TextStyle(
                  fontSize: 12,
                  color: AppTheme.textSecondaryColor,
                ),
                textAlign: TextAlign.center,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
              const SizedBox(height: 12),
              OutlinedButton.icon(
                onPressed: () => _showAddTemplateDialog(context, template),
                icon: const Icon(Icons.add),
                label: const Text('添加'),
                style: OutlinedButton.styleFrom(
                  foregroundColor: Color(template['color']),
                  side: BorderSide(color: Color(template['color'])),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
  
  void _showAddTemplateDialog(BuildContext context, Map<String, dynamic> template) {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('添加习惯模板'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('确定要添加"${template['name']}"到您的习惯列表吗？'),
            const SizedBox(height: 8),
            Text(
              '频率: ${template['frequency']}',
              style: AppTheme.bodyStyle,
            ),
            Text(
              '数量/时长: ${template['amount']}',
              style: AppTheme.bodyStyle,
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              final newHabit = Habit(
                name: template['name'],
                description: template['description'],
                icon: template['icon'],
                colorValue: template['color'],
                frequency: template['frequency'],
                amount: template['amount'],
              );
              
              Provider.of<HabitProvider>(context, listen: false).addHabit(newHabit);
              
              Navigator.of(context).pop();
              
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Text('已添加"${template['name']}"到您的习惯列表'),
                  behavior: SnackBarBehavior.floating,
                ),
              );
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: AppTheme.primaryColor,
            ),
            child: const Text('添加'),
          ),
        ],
      ),
    );
  }
}
